<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\Cities;
use App\Models\FilmTypeMaster;
use App\Models\MacroManagement;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\PartMaster;
use App\Models\Permissions;
use App\Models\PhoneExtension;
use App\Models\Roles;
use App\Models\ProductTypes;
use App\Models\ProvinceMaster;
use App\Models\RegionMaster;
use App\Models\RollSales;
use App\Models\Warranty;
use Encore\Admin\Grid\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;

class InitController extends Controller
{

    public function test()
    {
        /* $this->makeLangFile('cities');
        $this->makeLangFile('province_master');
        $this->makeLangFile('region_master');*/
        /*App::setLocale('zh_tw');
        $mod = Admin::find(76);*/
        // __('cities.'.$mod->city), Lang::get('province_master.'.$mod->province_id), $mod, App::getLocale()
    }
    public function test2()
    {
        $user = Admin::find(1);
        $user = Admin::find(2);
        session(['admin'=>$user]);
        session(['admin_sms_check' => 1]);
    }
    public function test3($id=null)
    {
        // 649
        $id = 75;
        $id = 79;
        $id = 2782;
        $user = Admin::withTrashed()->find($id);
        // $user = Admin::withTrashed()->find(1515);
        // $user->restore();
        /*$user->status=1;
        $user->save();*/
        session(['admin'=>$user]);

        session(['admin_sms_check' => 1]);
    }

    public function model1()
    {
        // SELECT `year_id`, `make_id`, `model_id`, `sub_model_id` FROM `warranty` WHERE 1
        $data = DB::table('warranty')->get(['year_id', 'make_id', 'model_id']);
        $vd = [];
        foreach ($data as $k => $v) {
            $ke = (int)($v->year_id).'###'.(int)($v->make_id).'###'.trim($v->model_id);
            $vd[$ke] = 1;
        }
        $vr = [];
        foreach ($vd as $k => $v) {
            $item = explode('###', $k);
            $item[3] = ts('make_master.'.$item[1]);
            $vr[] = $item;
        }
        return $vr;
        $vv = array_keys($vd);
        return $vv;
    }

    public function rollRestlen()
    {
        $data = DB::table('roll_sales as rs')
            ->leftJoin('roll_master as rm', 'rm.id', 'rs.roll_id')
/*            ->offset(0)
            ->limit(500)*/
            ->get(['rs.roll_id', 'rm.roll_number', 'rs.sold_by_user_id', 'rs.sold_to_user_id', 'rs.length', DB::raw('rm.length as t')]);
        return $data;
    }
    public function rollRestlen2()
    {
        $file = storage_path('app/template/20200927_roll_sales.json');
        /*$data = $this->rollRestlen();
        file_put_contents($file, json_encode($data));*/
        $data = file_get_contents($file);
        $data = json_decode($data);

        $ups = [];
        $admin = [];

        $c = DB::table('roll_restlen')->count();
        // 仅复制主表时的结果
        if ($c == 135322) {

        }
        foreach ($data as $k => $v) {
            $key1 = implode('###', [$v->sold_by_user_id, $v->roll_id, $v->roll_number]);
            $key2 = implode('###', [$v->sold_to_user_id, $v->roll_id, $v->roll_number]);
            if ($v->sold_by_user_id == 1) {
                if (!isset($ups[$key1])) {
                    $ups[$key1] = $v->t;
                }
            }
            $ups[$key1] = @$ups[$key1] - $v->length;
            $ups[$key2] = @$ups[$key2] + $v->length;
            /*if ($v->sold_by_user_id == 1 || empty($v->sold_by_user_id)) {

            } else {
                $ups[$key1] = @$ups[$key1] - $v->length;
            }
            if ($v->sold_to_user_id == 1 || empty($v->sold_to_user_id)) {

            } else {
                $ups[$key2] = @$ups[$key2] + $v->length;
            }*/
        }
        $file2 = storage_path('app/template/20200927_roll_sales_2.json');
        file_put_contents($file2, json_encode($ups));

        foreach ($ups as $k => $v) {

        }
        $this->test2();
        return [count($data), count($ups), array_slice($ups, 10, 10), $c];
    }
    public function rollRestlen3()
    {
        $file2 = storage_path('app/template/20200927_roll_sales_2.json');
        $data = file_get_contents($file2);
        $data = json_decode($data, 1);

        return $data;
    }
    public function rollRestlen4()
    {
        $file = storage_path('app/template/20200927_roll_master.json');
        $data = DB::table('roll_master')
            ->get(['id', 'roll_number','length']);
        file_put_contents($file, json_encode($data));
        return $data;
    }
    public function rollRestlen5()
    {
        $file = storage_path('app/template/20200927_roll_master.json');
        $data = file_get_contents($file);
        $data = json_decode($data);
        $roll_master = [];
        foreach ($data as $v) {
            $key1 = implode('###', [1, $v->id, $v->roll_number]);
            $roll_master[$key1] = $v->length;
        }

        $file = storage_path('app/template/20200927_roll_sales.json');
        $data = file_get_contents($file);
        $data = json_decode($data);
        foreach ($data as $k => $v) {
            $key1 = implode('###', [$v->sold_by_user_id, $v->roll_id, $v->roll_number]);
            $key2 = implode('###', [$v->sold_to_user_id, $v->roll_id, $v->roll_number]);
            if ($v->sold_by_user_id == 1) {
                if (!isset($ups[$key1])) {
                    $ups[$key1] = $v->t;
                }
            }
            $roll_master[$key1] = @$roll_master[$key1] - $v->length;
            $roll_master[$key2] = @$roll_master[$key2] + $v->length;
        }

        return $roll_master;
    }
    public function warranty_image() {
        $images = DB::table('warranty')->select('id', 'image_front', 'image_back', 'image_driver_side', 'image_passenger_side')
            ->orderBy('id')
            ->get();
        $uploads = [];
        $time = date('Y-m-d H:i:s');
        $p = [
            'image_front' => 1,
            'image_back' => 2,
            'image_driver_side' => 3,
            'image_passenger_side' => 4,
        ];
        foreach ($images as $k => $v) {
            foreach ($p as $x => $y) {
                $item = [
                    'warranty_id' => $v->id,
                    'part_id' => $y,
                    'image_src' => $v->$x,
                    'created_at' => $time,
                    'updated_at' => $time,
                ];
                $uploads[] = array_values($item);
            }
        }
        $string = json_encode($uploads);
        $search = ['[[', '[', ']]', ']'];
        $repace = ['(', '(', ')', ')'];
        $string = str_replace($search, $repace, $string);
        $ins = "INSERT INTO warranty_image (warranty_id, part_id, image_src, created_at, updated_at) VALUES \n";
        $sql = $ins.$string."; \n";
        $filename = storage_path('app/template/warranty_image.sql');
        file_put_contents($filename, $sql); // 如果文件已存在，追加数据, FILE_APPEND

    }
    /*
     * 权限管理*/
    public function permiss()
    {
        /*$menu = [
            '客户管理',
            '产品管理',
            '质保管理',
            '审核管理',
            '监控中心',
            '数据字典',
        ];
        foreach ($menu as $v) {
            $model = new Permissions();
            $model->english_value = $v;
            $model->traditional_chiness_value = $v;
            $model->simplified_chiness_value = $v;
            $model->type = 1;
            $model->save();
        }*/
        /*$menu2 = [
            1 => [
                '省代管理',
                '经销商管理',
                '车主管理',
            ],
            2 => [
                '膜管理',
                '批量导入',
                '专车专用套件',
            ],
            4 => [
                '质保审核',
                '调货审核',
                '套餐退货管理',
                '膜退货管理',
            ],
            5 => [
                '操作记录',
                '数据库操作记录',
                '经销商同步',
                '休眠省代管理',
                '休眠经销商管理',
            ],
            6 => [
                '膜的种类',
                '品牌',
                '车型',
                '静态文本管理',
            ],
        ];
        foreach ($menu2 as $k => $o) {
            foreach ($o as $v) {
                $model = new Permissions();
                $model->english_value = $v;
                $model->traditional_chiness_value = $v;
                $model->simplified_chiness_value = $v;
                $model->parent_id = $k;
                $model->type = 1;
                $model->save();
            }
        }*/
    }

    public function rollsTest()
    {
        $roll_number = '64578903';
        $user_id = 1;

        $roll = getRollsMasterByRollNumber($roll_number);
        $rs = RollSales::where('roll_id', $roll->id)->get();
        if ($user_id == 1) {
            $length = $roll->length;
        } else {
            $length = 0;
        }
        foreach ($rs as $k => $v) {
            /*出售方*/
            if ($v->sold_by_user_id == $user_id) {
                $length -= $v->length;
            }
            /*
             * 获得方*/
            if ($v->sold_to_user_id == $user_id) {
                $length += $v->length;
            }
        }

        $len1 = DB::table('warranty_to_vehicle_coverage as tvc')
            ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
            ->where('tvc.roll_number', $roll_number)
            ->where('w.approved', '!=', 3)
            ->where('w.id', '>=', 1)
            ->where('w.user_id', $user_id)
            ->sum('length');
        $len2 = DB::table('precut_to_vehicle_coverage as tvc')
            ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
            ->leftJoin('warranty as w', 'w.pre_id', 'p.id')
            ->whereNull('w.id')
            ->where('tvc.roll_number', $roll_number)
            ->where('p.id', '>=', 1)
            ->where('p.created_by', $user_id)
            ->sum('length');
        $len1 = $len1 >0 ? $len1 : 0;
        $len2 = $len2 >0 ? $len2 : 0;
        return [$len1, $len2, $rs, $length, $roll->id];
        return $length - ($len1+$len2);

        return [getRlenV401('64578903')];

    }

    /*
     * 获取剩余长度*/
    function getRestlenV3() {
        $roll_number = '64578903';
        $roll = getRollsMasterByRollNumber($roll_number);
        $len1 = DB::table('warranty_to_vehicle_coverage as tvc')
            ->leftJoin('warranty as w', 'w.id', 'tvc.warranty_id')
            ->where('tvc.roll_number', $roll_number)
            ->where('w.approved', '!=', 3)
            ->where('w.id', '>=', 1)
            ->whereNull('w.deleted_at')
            ->get();
            //->sum('length');
        $len2 = DB::table('precut_to_vehicle_coverage as tvc')
            ->leftJoin('precut as p', 'p.id', 'tvc.precut_kit_sale_id')
            ->leftJoin('warranty as w', 'w.pre_id', 'p.id')
            ->whereNull('w.id')
            ->where('tvc.roll_number', $roll_number)
            ->where('p.id', '>=', 1)
            ->where('w.approved', '!=', 3)
            ->sum('length');
        return [$len1];
    }
    public function t6()
    {

        $dtime = gDate();
        $yty = ['21X97cQYEBx3obXLT94rthn9r9I0sN8a.jpeg',
            'E9WH4NQgegaZH4WrFxwTozfRG1QlWi2W.jpeg',
            'Yd1LGTGr4iPvkAjl9oDZpcDFrEW7rIeO.jpeg',
            '4d1O9qTspULhGXIYGm7hUPUCZ8YKmudW.jpeg',
            'tSdFFppw2T6VzmPDnxNP4LY0MTJBNtYn.jpeg',
            'FrU3wtBdRmWcQDJHqDfWFKFNg1SgPXnK.jpeg',];
        $wid = 10106208;
        /*$yty = ['NzX0e3fMlGSg1tNmmgVU89ecDzgiULzz.gif',
            'sZ71jmFw99fuS2UEAtVXW642FeLLdzDz.jpeg',
            '74R9ZA4bitCrHCE77XldvtsH91pzzuFK.jpeg',
            'L5PMVTjHL2Qns3HqNKn379ruROh4eCGR.gif',
            'mAo2IW3M3YtRTVQy9nP7v70b8hHZsaMi.gif',
            'yGLcartpYnyge5SNVrV8bC9qxpknamdO.jpeg',
            'u0y8IrlocoGDlkQrsWT1A8jz4OFnHnUA.jpeg',
            'bJICYb3LBZ8UwZjy4FgfGQrMlvB2CbhM.jpeg',
            'iEd3wUwPK1pBEz5jjeulSpuol8S1HuVW.jpeg',
            'tZYez4eMTxzRat4KgwOSg6zJhoswhsAk.jpeg',
            'NXUNZlZlTD0R7ZKRum7bh3YYm3sFjRUA.jpeg',
            'OBCvh5KzwM714eJLZGn2WJ0EujGjRCRy.jpeg',];
        $wid = 10106210;*/
        $yty = array_unique($yty);
        foreach ($yty as $k => $v) {

            $item = [];
            $item['warranty_id'] = $wid;
            $item['created_at'] = $dtime;
            $item['updated_at'] = $dtime;
            $item['image_src'] = $v;
            $item['part_id'] = $k+1;
            $imgs[] = $item;
        }
        DB::table('warranty_image')->where('warranty_id', $wid)->delete();
        DB::table('warranty_image')->insert($imgs);
    }

    protected function testRollLen()
    {
        $roll_number = '2610971';
        $r1 = getRlenV401($roll_number);
        $r1 = getRestlenV3($roll_number);
        $roll = getRollsMasterByRollNumber($roll_number);
        $len1 = DB::table('roll_sales')
            ->where('roll_id', $roll->id)
            ->where('sold_by_user_id', 1)
            ->sum('length');
        $len2 = DB::table('roll_sales')
            ->where('roll_id', $roll->id)
            ->where('sold_to_user_id', 1)
            ->sum('length');

        $user_id = 72;
        $q = '2';
        $sold_by = DB::table('roll_sales')
            ->where('sold_by_user_id', $user_id)
            ->whereNull('deleted_at')
            ->select([DB::raw('sum(length) as len'), 'roll_id'])
            ->groupBy('roll_id');
        $sold_to = DB::table('roll_sales')
            ->where('sold_to_user_id', $user_id)
            ->whereNull('deleted_at')
            ->select([DB::raw('sum(length) as len'), 'roll_id'])
            ->groupBy('roll_id');
        $rs = DB::table($sold_by, 'sold_by')
            ->leftJoinSub($sold_to, 'sold_to', 'sold_by.roll_id', 'sold_to.roll_id')
            ->select([DB::raw('(sold_to.len-sold_by.len) as restlen'), 'sold_by.roll_id']);

        $pl = DB::table('precut_to_vehicle_coverage as tvc')
            ->leftJoin('precut as p', 'tvc.precut_kit_sale_id', 'p.id')
            ->whereNull('p.deleted_at')
            ->whereNull('tvc.deleted_at')
            ->where('p.created_by', $user_id)
            ->groupBy('tvc.roll_number')
            ->select([DB::raw('sum(length) as len'), 'roll_number']);

        $wl = DB::table('warranty_to_vehicle_coverage as tvc')
            ->leftJoin('warranty as w', 'tvc.warranty_id', 'w.id')
            ->whereNull('w.deleted_at')
            ->whereNull('tvc.deleted_at')
            ->where('w.approved', '=', 1)
            ->where('w.user_id', $user_id)
            ->groupBy('tvc.roll_number')
            ->select([DB::raw('sum(length) as len'), 'roll_number']);

        $wp = DB::table($wl, 'wvc')
            ->leftJoinSub($pl, 'pvc', 'wvc.roll_number', 'pvc.roll_number')
            ->select([DB::raw('(wvc.len+pvc.len) as usedlen'), 'wvc.roll_number']);

        $model = DB::table('roll_master as rm')
            ->leftJoinSub($rs, 'rs', 'rs.roll_id', 'rm.id')
            ->leftJoinSub($wp, 'us', 'rm.roll_number', 'us.roll_number')
            ->leftJoin('film_type_master as ftm', 'ftm.id', 'rm.film_type_id')
            ->where('rm.roll_number', 'like', ''.$q.'%')
            ->whereNull('rm.deleted_at')
            ->select(['rm.id', 'rm.roll_number', 'rm.length', 'rs.restlen', 'rs.roll_id', DB::raw('(rs.restlen - us.usedlen) as rest')]);
        if ($user_id == 1) {
            /*$model = $model->where(function ($query) {
                $query->where('rs.restlen', '>', 0)
                    ->orWhereNull('rs.roll_id');
            });*/
            $model = $model->where(function ($query) {
                $query->where(DB::raw('(rs.restlen - us.usedlen) > 0'))
                    ->orWhere(function ($dquery) {
                        $dquery->whereNull('rs.roll_id')
                            ->where(DB::raw('(rm.length - us.usedlen) > 0'));
                    });
            });
        } else {
            $model = $model->where(DB::raw('(rs.restlen - us.usedlen) > 0'));
            // $model = $model->where('rs.restlen', '>', 0);
        }


        $roll = $model->limit(20)
            ->get();


        // $model->toSql()
        return [$r1, $model->toSql(), $len1, $len2, $roll, $user_id];
    }


    /*
     * 国际短信发送*/
    /*
     *{"status":"error","code":254,"msg":"Can not match the International Phone number"}
     * {
        "status":"success"
        "send_id":"093c0a7df143c087d6cba9cdf0cf3738"
        "fee":0.046,
        "account_balance":14197.087
    }*/
    function international_sms_send($phone, $content) {
        $config = [
            'appid' => '61611',
            'appkey' => '83aba62894ad6b0c2d7d54132b5fd066',
            'sign_type' => 'normal',
            'server' => 'https://api.mysubmail.com/',
        ];
        $submail=new \INTERNATIONALSMSsend($config);
        $submail->setTo($phone);
        $submail->SetContent($content);
        $xsend=$submail->send();
        return $xsend;
    }

    //
    public function init(Request $request)
    {
        if ($request->input('t')==2) {
            $this->test3();
        } elseif($request->input('t')==1) {
            $this->test2();
        }
        return [5];
        /*$up = [];
        foreach (range(1,8) as $v) {
            $pwd = makePassword();
            $admin = Admin::find($v);
            $admin->password = bcrypt($pwd);
            $admin->save();
            $up[] = [
                'user' => $admin->unique_id,
                'pwd' => $pwd,
            ];
        }
        return [$up];*/

        /*$admin = Admin::find(2);
        $admin->password = bcrypt('ig6XLxFCghmrJZYP');
        $admin->save();*/
        return [];
        /*$phone = '18817354090';
        $content = '尊敬的客戶, 謝謝您選擇！';
        return $this->international_sms_send($phone, $content);*/

        /*$preg = '/^[京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[A-Z]{1}[A-Z0-9]{5}[DF]{0,1}$/u';
        $preg = '/^(([京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[A-Z]{1})[-]?|([wW][Jj][京津沪渝蒙新藏宁桂黑吉辽晋冀青鲁豫苏皖浙闽赣湘鄂粤琼甘陕贵云川港澳台]{1}[-]?)|([a-zA-Z]{2}))([A-Za-z0-9]{5}|[DdFf][A-HJ-NP-Za-hj-np-z0-9][0-9]{4}|[0-9]{5}[DdFf])$/u';
        $license_plate = "京A12345";
        $e = pregV1('license_plate', $license_plate);
        $f = preg_match($preg, $e);
        return [$e, $f];*/

        if ($request->input('t')==2) {
            $this->test3();
        } else {
            $this->test2();
        }
        return [];
        return $this->test3();
        return $this->test2();
        return $this->testRollLen();

        $this->test3();
        return $this->getRestlenV3();
        return $this->rollsTest();

        return $this->test3();
        /*$roles = Roles::findOrNew(4);
        $roles->name = '测试';
        $roles->save();
        $roles->permissions()->sync([9,18,15,13]);*/
        // $this->permiss();
        // $this->warranty_image();

        /*foreach (range(2, 2689) as $v) {
            $admin = Admin::withTrashed()->find($v);
            if ($admin) {
                $admin->unique_id = Str::random(32);
                $admin->save();
            }
        }*/
        // DB::table('users')->update(['deleted_at' => date('Y-m-d H:i:s')]);
        if ($request->input('t')==2) {
            $this->test3();
        } else {
            $this->test2();
        }
        return [];
        set_time_limit(0);
        // $data = $this->rollRestlen5();
        $file2 = storage_path('app/template/20200927_roll_restlen.json');
        $data = file_get_contents($file2);
        $data = json_decode($data);
        $c = DB::table('roll_restlen')->count();
        // 仅复制主表时的结果

        $ee = [];
        return [];
        $ek = 296804    ;
        if ($c == $ek ) {
            $i = 0;
            foreach ($data as $k => $v) {
                if ($i<$ek ) {
                    $i ++;
                    continue;
                }
                $item = [];
                $d = explode('###', $k);
                $item = [
                    'user_id' => $d[0],
                    'roll_id' => $d[1],
                    'roll_number' => $d[2],
                    'restlen' => $v,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                if (empty($ee)) {
                    $ee = $item;
                }
                $datas[] = $item;
                if (count($datas) == 5000) {
                    DB::table('roll_restlen')->insert($datas);
                    $datas = [];
                }
            }
            if (count($datas)) {
                DB::table('roll_restlen')->insert($datas);
            }
            return [0, count($datas), $ee];
        }
        return [$ee, $c];

        // $this->test2();
        /*makeLangFile('part_master');
        makeLangFile('film_type_master');*/
        # $this->test2();
        $table = $request->input('table');
        $page = $request->input('page') ?: 1;
        $data = [];
        $next = '';
        $time = time();
        /*$this->users();
        $this->cities();
        $this->makeLangFile('cities');
        $this->makeLangFile('province_master');
        $this->makeLangFile('region_master');
        $this->macro_management();
        $this->makeLangFile('macro_management');
        $this->part_master();*/

        /*$this->film_type_master();
        $this->make_master();
        $this->model_master();*/
        /*$this->product_types();*/
        // makeLangFile('product_types');
        // makeLangFile('make_master');
        # $data = $this->warranty2($request);
        # $data = $this->warranty_to_vehicle_coverage($request);
        # $data = $this->precut_kit($request);
        # $data = $this->roll_master($request);
        # $data = $this->phone_extension($request);
        return $data;
    }
    protected function phone_extension(Request $request)
    {
        $datas = DB::connection('mysql2')->table('phone_extension')->get();
        foreach ($datas as $k => $v) {
            $mod = PhoneExtension::findOrNew($v->id);
            $mod->id = $v->id;
            $mod->phone_ext = $v->phone_ext;
            $mod->save();
        }
    }
    protected function roll_master(Request $request)
    {
        $roll_master =  DB::table('roll_master')->update([
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $roll_sales =  DB::table('roll_sales')->update([
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        return [$roll_master, $roll_sales];
    }
    protected function precut_kit(Request $request)
    {
        $precut_kit =  DB::table('precut_kit')->update([
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $precut_kit_sales =  DB::table('precut_kit_sales')->update([
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $precut_to_vehicle_coverage =  DB::table('precut_to_vehicle_coverage')->update([
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        return [$precut_kit, $precut_kit_sales, $precut_to_vehicle_coverage];
    }

    protected function warranty_to_vehicle_coverage(Request $request)
    {
        $bool =  DB::table('warranty_to_vehicle_coverage')->update([
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        return [$bool];
    }

    protected function warranty2(Request $request)
    {
       $bool =  DB::table('warranty')->update([
            'approved' => 1,
            'approved_by_user_id' => 1,
            'approved_date' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
       return [$bool];
    }
    // 禁用，改为数据库迁移，修改自动、补充数据
    protected function warranty(Request $request)
    {
        $page = $request->input('page') ?: 1;
        $total = DB::connection('mysql2')->table('warranty')->count();
        $limit = 2000;
        $total_page = ceil($total / $limit) ;
        $datas = DB::connection('mysql2')->table('warranty')->paginate($limit);
        foreach ($datas as $k => $v) {
            $mod = Warranty::findOrNew($v->warranty_id);
            $mod->id = $v->warranty_id;
            $mod->user_id = $v->user_id;
            $mod->first_name = $v->first_name;
            $mod->last_name = $v->last_name;
            $mod->address = $v->address;
            $mod->city = $v->city;
            $mod->province_id = $v->province_id;
            $mod->zip = $v->zip;
            $mod->region_id = $v->region_id;
            $mod->email_address = $v->email_address;
            $mod->phone_number = $v->phone_number;
            $mod->installer_name = $v->installer_name;
            $mod->installation_date = $v->installation_date;
            $mod->installation_price = $v->installation_price;
            $mod->image_front = $v->image_front;
            $mod->image_back = $v->image_back;
            $mod->image_driver_side = $v->image_driver_side;
            $mod->image_passenger_side = $v->image_passenger_side;
            $mod->year_id = $v->year_id;
            $mod->make_id = $v->make_id;
            $mod->model_id = $v->model_id;
            $mod->sub_model_id = $v->sub_model_id;
            $mod->license_plate = $v->license_plate;
            $mod->vin_number = $v->vin_number;
            $mod->additional_comments = $v->additional_comments;
            $mod->vehicle_coverage_id = $v->vehicle_coverage_id;
            $mod->pre_id = $v->pre_id;
            $mod->language_id = $v->language_id;
            $mod->extension = $v->extension;

            $mod->approved = 1;
            $mod->approved_by_user_id = 1;
            $mod->approved_date = date('Y-m-d H:i:s');
            $mod->save();
        }
        if ($page < $total_page) {
            return redirect('/'.request()->path().'/?page='.($page+1));
        }
        return [$mod->id, $page, $total_page];
    }

    protected function product_types()
    {
        $datas = DB::connection('mysql2')->table('product_types')->get();
        foreach ($datas as $k => $v) {
            $mod = ProductTypes::findOrNew($v->id);
            $mod->id = $v->id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->name); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->save();
        }
    }

    // 膜的种类管理
    protected function film_type_master()
    {
        $datas = DB::connection('mysql2')->table('film_type_master')->get();
        foreach ($datas as $k => $v) {
            $mod = FilmTypeMaster::findOrNew($v->film_type_id);
            $mod->id = $v->film_type_id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->film_type_name); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->product_type_id = $v->product_type_id;
            $mod->save();
        }
    }

    // 品牌
    protected function make_master()
    {
        $datas = DB::connection('mysql2')->table('make_master')->get();
        foreach ($datas as $k => $v) {
            $mod = MakeMaster::findOrNew($v->make_id);
            $mod->id = $v->make_id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->make_name); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->year_id = $v->year_id;
            $mod->save();
        }
    }
    // 车型
    protected function model_master()
    {
        $datas = DB::connection('mysql2')->table('model_master')->get();
        foreach ($datas as $k => $v) {
            $mod = ModelMaster::findOrNew($v->model_id);
            $mod->id = $v->model_id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->model_name); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->make_id = $v->make_id;
            $mod->save();
        }
    }


    // 静态文本管理
    protected function macro_management()
    {
        $datas = DB::connection('mysql2')->table('macro_management')->get();
        foreach ($datas as $k => $v) {
            $mod = MacroManagement::findOrNew($v->macro_id);
            $mod->id = $v->macro_id;
            $mod->macro_name = $v->macro_name;
            $mod->english_value = $v->english_value;
            $zt = trim($v->traditional_chiness_value);
            $zs = trim($v->simplified_chiness_value);
            if (mb_stripos($zt, '&#')===0) {
                $zt = str_replace('&#', ';&#', $zt).';';
                $zt = mb_substr($zt, 1);
            }
            if (mb_stripos($zs, '&#')===0) {
                $zs = str_replace('&#', ';&#', $zs).';';
                $zs = mb_substr($zs, 1);
            }
            $mod->traditional_chiness_value = html_entity_decode($zt);
            $mod->simplified_chiness_value = html_entity_decode($zs);
            $mod->link = $v->link;
            $mod->link_t = $v->link_t;
            $mod->link_s = $v->link_s;
            $mod->save();
        }
    }

    protected function makeLangFile($table)
    {
        return makeLangFile($table);
        $label = 'id';
        $dir = resource_path('lang');
        $filename = $table.'.php';
        if ($table == 'cities') {
            $data = Cities::get();
        }
        if ($table == 'province_master') {
            $data = ProvinceMaster::get();
        }
        if ($table == 'region_master') {
            $data = RegionMaster::get();
        }
        if ($table == 'macro_management') {
            $label = 'macro_name';
            $data = MacroManagement::get();
        }
        if ($table == 'product_types') {
            $data = ProductTypes::get();
        }
        $prefix = '<?php'."\n\n".'return ['."\n";
        $suffix = '];';
        $en = $zh_tw = $zh = '';
        foreach ($data as $k =>$v) {
            $en .= '    "'.$v->$label . '" => "' .  $v->english_value . '",' ."\n";
            $zh_tw .= ' "'.$v->$label . '" => "' .  $v->traditional_chiness_value . '",' ."\n";
            $zh .= '    "'.$v->$label . '" => "' .  $v->simplified_chiness_value . '",' ."\n";
        }
        file_put_contents($dir . '/en/' . $filename, $prefix.$en.$suffix);
        file_put_contents($dir . '/zh/' . $filename, $prefix.$zh.$suffix);
        file_put_contents($dir . '/zh_tw/' . $filename, $prefix.$zh_tw.$suffix);
        return true;
    }

    // cities表、province_master表与region_master迁移
    protected function cities()
    {
        $datas = DB::connection('mysql2')->table('cities')->get();
        foreach ($datas as $k => $v) {
            $mod = Cities::findOrNew($v->city_id);
            $mod->id = $v->city_id;
            $mod->province_id = $v->province_id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->city); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->save();
        }
        $datas = DB::connection('mysql2')->table('province_master')->get();
        foreach ($datas as $k => $v) {
            $mod = ProvinceMaster::findOrNew($v->province_id);
            $mod->id = $v->province_id;
            $mod->region_id = $v->region_id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->province_name); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->save();
        }
        $datas = DB::connection('mysql2')->table('region_master')->get();
        foreach ($datas as $k => $v) {
            $mod = RegionMaster::findOrNew($v->region_id);
            $mod->id = $v->region_id;
            $mod->english_value = empty($mod->english_value) ? '' : $mod->english_value;
            $mod->traditional_chiness_value = empty($mod->traditional_chiness_value) ? '' : $mod->traditional_chiness_value;
            $mod->simplified_chiness_value = empty($mod->simplified_chiness_value) ? '' : $mod->simplified_chiness_value;
            $name = html_entity_decode($v->region_name); # 转义实体字符
            if ($v->language_id == 1) {
                $mod->english_value = $name;
            } elseif ($v->language_id == 2) {
                $mod->traditional_chiness_value = $name;
            } elseif ($v->language_id == 3) {
                $mod->simplified_chiness_value = $name;
            }
            $mod->save();
        }
        return true;
    }

    // 用户表迁移
    protected function users()
    {
        $datas = DB::connection('mysql2')->table('users')->get();
        foreach ($datas as $k => $v) {
            $user = Admin::findOrNew($v->user_id);
            $user->id = $v->user_id;
            $user->creator_id = $v->creator_id;
            $user->user_type = $v->user_type;
            $user->unique_id = $v->unique_id;
            $user->company_name = $v->company_name;
            $user->first_name = $v->first_name;
            $user->last_name = $v->last_name;
            $user->username = $v->username;
            $user->email_address = $v->email_address;
            $user->password = $v->password;
            $user->address = $v->address;
            $user->city = $v->city;
            $user->province_id = $v->province_id;
            $user->zip = $v->zip;
            $user->region_id = $v->region_id;
            $user->phone_number = $v->phone_number;
            $user->note = $v->note;
            $user->cell_phone = $v->cell_phone;
            $user->wechat_id = $v->wechat_id;
            $dsp = strtotime($v->date_signedup);
            if (!empty($dsp) && $dsp>0) {
                $date_signedup = $v->date_signedup;
            } else {
                $date_signedup = date('Y-m-d H:i:s');
            }
            $user->date_signedup = $date_signedup;
            $user->additional_comment = $v->additional_comment;
            $user->province = $v->province;
            $user->status = $v->status;
            $user->language_id = $v->language_id;
            $user->extension = $v->extension;
            $user->save();
        }
    }

    protected function part_master()
    {
        $datas = DB::connection('mysql2')->table('part_master')->get();
        foreach ($datas as $k => $v) {
            $min_length = 0;
            $select_part = $v->part_name;
            if($select_part == "Other" || $select_part == "其他（局部套餐）" || $select_part == "其它（局部套餐）"){
                $min_length = 10;
            }
            if($select_part == "Bumper" || $select_part == "前保險槓" || $select_part == "前保险杠"){
                $min_length = 140;
            }
            if($select_part == "Rear Bumper" || $select_part == "後保險槓" || $select_part == "后保险杠"){
                $min_length = 150;
            }
            if($select_part == "Hood" || $select_part == "引擎蓋" || $select_part == "机盖"){
                $min_length = 180;
            }
            if($select_part == "Fender" || $select_part == "前葉子板" || $select_part == "前叶子板"){
                $min_length = 120;
            }
            if($select_part == "Single Fender" || $select_part == "單片前葉子板" || $select_part == "單片前葉子板"){
                $min_length = 76;
            }
            if($select_part == "Door" || $select_part == "門" || $select_part == "门"){
                $min_length = 250;
            }
            if($select_part == "Single Door" || $select_part == "單個門" || $select_part == "單個門"){
                $min_length = 65;
            }
            if($select_part == "Rear Fender" || $select_part == "後葉子板" || $select_part == "后叶子板"){
                $min_length = 300;
            }
            if($select_part == "Single Rear Fender" || $select_part == "單片後葉子板" || $select_part == "單片後葉子板"){
                $min_length = 150;
            }
            if($select_part == "Roof" || $select_part == "車頂" || $select_part == "车顶"){
                $min_length = 150;
            }
            if($select_part == "Rocker" || $select_part == "側裙" || $select_part == "侧裙"){
                $min_length = 30;
            }
            if($select_part == "Door Cup" || $select_part == "手把碗公" || $select_part == "门杯"){
                $min_length = 5;
            }
            if($select_part == "Headlight" || $select_part == "大燈" || $select_part == "大灯"){
                $min_length = 25;
            }
            if($select_part == "Rear View Mirror" || $select_part == "後視鏡" || $select_part == "后视镜"){
                $min_length = 10;
            }
            if($select_part == "Trunk Lid" || $select_part == "行李箱" || $select_part == "行李箱"){
                $min_length = 80;
            }
            if($select_part == "Full Front" || $select_part == "全車頭 (引擎蓋+葉子板+前保險槓)" || $select_part == "全车头（引擎盖+叶子板+前保险杠）"){
                $min_length = 480;
            }
            if($select_part == "Full Car" || $select_part == "全車" || $select_part == "全车"){
                $min_length = 1200;
            }
            if($select_part == "Other" || $select_part == "其他" || $select_part == "其他"){
                $min_length = 10;
            }
            if($select_part == "Hood & Bumper" || $select_part == "引擎蓋+葉子板" || $select_part == "引擎盖+叶子板"){
                $min_length = 50;
            }
            if($select_part == "ASP Bikini Hood & Bumper" || $select_part == "ASP Bikini 引擎蓋+葉子板" || $select_part == "ASP Bikini 引擎蓋+葉子板"){
                $min_length = 50;
            }
            if($select_part == "B-Pillar" || $select_part == "B柱" || $select_part == "B柱"){
                $min_length = 10;
            }
            if($select_part == "ASP Interior Kit" || $select_part == "ASP 內飾套餐" || $select_part == "ASP 内饰套餐"){
                $min_length = 0;
            }
            if($select_part == "ASP Partial Kit" || $select_part == "ASP 局部套餐" || $select_part == "ASP 局部套餐"){
                $min_length = 0;
            }
            if($select_part == "General Interior Kit" || $select_part == "一般內飾套餐" || $select_part == "一般内饰套餐"){
                $min_length = 80;
            }
            if($select_part == "Steering Column Cover" || $select_part == "土除" || $select_part == "土除"){
                $min_length = 10;
            }
            if($select_part == "Front Shield of Vehicle frame" || $select_part == "斜板" || $select_part == "斜板"){
                $min_length = 10;
            }
            if($select_part == "Engine Cowl and vehicle Frame-Both sides" || $select_part == "左右車身" || $select_part == "左右车身"){
                $min_length = 600;
            }
            if($select_part == "Handlebar Housing and dashboard" || $select_part == "車首蓋" || $select_part == "车首盖"){
                $min_length = 180;
            }
            if($select_part == "Side Step Cover-Both Sides" || $select_part == "左右關刀" || $select_part == "左右关刀"){
                $min_length = 10;
            }
            if($select_part == "Font Storage" || $select_part == "手套箱" || $select_part == "手套箱"){
                $min_length = 10;
            }
            if($select_part == "Font Steps" || $select_part == "手套箱下方" || $select_part == "手套箱下方"){
                $min_length = 10;
            }
            $part = PartMaster::findOrNew($v->part_id);
            $part->id = $v->part_id;
            $part->min_length = $part->min_length ?: $min_length;
            $part->english_value = empty($part->english_value) ? '' : $part->english_value;
            $part->traditional_chiness_value = empty($part->traditional_chiness_value) ? '' : $part->traditional_chiness_value;
            $part->simplified_chiness_value = empty($part->simplified_chiness_value) ? '' : $part->simplified_chiness_value;
            if ($v->language_id == 1) {
                $part->english_value =$v->part_name;
            } elseif ($v->language_id == 2) {
                $part->traditional_chiness_value =$v->part_name;
            } elseif ($v->language_id == 3) {
                $part->simplified_chiness_value =$v->part_name;
            }
            $part->product_type_id =$v->product_type_id;
            $part->visibility =$v->visibility;
            $part->order =$v->order;
            $part->save();
        }
        return true;

    }


    protected function makeCitiesLang()
    {
        $data = Cities::get();
        $prefix = '<?php return [';
        $suffix = '];';
        $en = $zh_tw = $zh = '';
        foreach ($data as $k =>$v) {
            $en .= '"'.$v->id . '" => "' .  $v->english_value . '",' ."\n";
            $zh_tw .= '"'.$v->id . '" => "' .  $v->traditional_chiness_value . '",' ."\n";
            $zh .= '"'.$v->id . '" => "' .  $v->simplified_chiness_value . '",' ."\n";
        }
        $dir = resource_path('lang');
        $filename = 'cities.php';
        file_put_contents($dir . '/en/' . $filename, $prefix.$en.$suffix);
        file_put_contents($dir . '/zh/' . $filename, $prefix.$zh.$suffix);
        file_put_contents($dir . '/zh_tw/' . $filename, $prefix.$zh_tw.$suffix);

        $data = ProvinceMaster::get();
        $prefix = '<?php return [';
        $suffix = '];';
        $en = $zh_tw = $zh = '';
        foreach ($data as $k =>$v) {
            $en .= '"'.$v->id . '" => "' .  $v->english_value . '",' ."\n";
            $zh_tw .= '"'.$v->id . '" => "' .  $v->traditional_chiness_value . '",' ."\n";
            $zh .= '"'.$v->id . '" => "' .  $v->simplified_chiness_value . '",' ."\n";
        }
        $dir = resource_path('lang');
        $filename = 'province_master.php';
        file_put_contents($dir . '/en/' . $filename, $prefix.$en.$suffix);
        file_put_contents($dir . '/zh/' . $filename, $prefix.$zh.$suffix);
        file_put_contents($dir . '/zh_tw/' . $filename, $prefix.$zh_tw.$suffix);

        $data = RegionMaster::get();
        $prefix = '<?php return [';
        $suffix = '];';
        $en = $zh_tw = $zh = '';
        foreach ($data as $k =>$v) {
            $en .= '"'.$v->id . '" => "' .  $v->english_value . '",' ."\n";
            $zh_tw .= '"'.$v->id . '" => "' .  $v->traditional_chiness_value . '",' ."\n";
            $zh .= '"'.$v->id . '" => "' .  $v->simplified_chiness_value . '",' ."\n";
        }
        $dir = resource_path('lang');
        $filename = 'region_master.php';
        file_put_contents($dir . '/en/' . $filename, $prefix.$en.$suffix);
        file_put_contents($dir . '/zh/' . $filename, $prefix.$zh.$suffix);
        file_put_contents($dir . '/zh_tw/' . $filename, $prefix.$zh_tw.$suffix);
    }
}
